package cn.iocoder.yudao.module.erp.service.contacts.supplier;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.datapermission.core.util.DataPermissionUtils;
import cn.iocoder.yudao.module.erp.controller.admin.contacts.supplier.vo.SupplierImportExcelVO;
import cn.iocoder.yudao.module.erp.controller.admin.contacts.supplier.vo.SupplierImportRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.contacts.supplier.vo.SupplierPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.contacts.supplier.vo.SupplierSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.business.group.suppliergroup.SupplierGroupDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.contacts.supplier.SupplierDO;
import cn.iocoder.yudao.module.erp.dal.mysql.business.group.suppliergroup.SupplierGroupMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.contacts.supplier.SupplierMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;

/**
 * 供应商 Service 实现类
 *
 * @author maxuxu
 */
@Service
@Validated
@Slf4j
public class SupplierServiceImpl implements SupplierService {

    @Resource
    private SupplierMapper supplierMapper;
    @Resource
    private SupplierGroupMapper supplierGroupMapper;

    @Override
    public Long createSupplier(SupplierSaveReqVO createReqVO) {
        // 插入
        SupplierDO supplier = BeanUtils.toBean(createReqVO, SupplierDO.class);
        log.debug("SupplierServiceImpl.createSupplier(createReqVO) - [{}]", supplier);
        supplierMapper.insert(supplier);
        // 返回
        return supplier.getId();
    }

    @Override
    public void updateSupplier(SupplierSaveReqVO updateReqVO) {
        // 校验存在
        validateSupplierExists(updateReqVO.getId());
        // 更新
        SupplierDO updateObj = BeanUtils.toBean(updateReqVO, SupplierDO.class);
        supplierMapper.updateById(updateObj);
    }

    @Override
    public void deleteSupplier(Long id) {
        // 校验存在
        validateSupplierExists(id);
        // 删除
        supplierMapper.deleteById(id);
    }

    private void validateSupplierExists(Long id) {
        if (supplierMapper.selectById(id) == null) {
            throw exception(SUPPLIER_NOT_EXISTS);
        }
    }

    @Override
    public SupplierDO getSupplier(Long id) {
        return supplierMapper.selectById(id);
    }

    @Override
    public PageResult<SupplierDO> getSupplierPage(SupplierPageReqVO pageReqVO) {
        return supplierMapper.selectPage(pageReqVO);
    }

    @Override
    public void deleteSuppliers(Collection<Long> idList) {
        if (CollUtil.isEmpty(idList)) {
            return;
        }
        supplierMapper.deleteBatchIds(idList);
    }
    private void validateSupplierForCreateOrUpdate(Long id, String username) {
        // 关闭数据权限，避免因为没有数据权限，查询不到数据，进而导致唯一校验不正确
        DataPermissionUtils.executeIgnore(() -> {
            // 校验客户存在
//            validateCustomerExists(id);
            // 校验客户名称名唯一
//            validateCustomerUnique(id, username);
        });
    }
    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有导入
    public SupplierImportRespVO importSupplierList(List<SupplierImportExcelVO> importSuppliers, Boolean isUpdateSupport, Long loginUserId) {
        if (CollUtil.isEmpty(importSuppliers)) {
            throw exception(SUPPLIER_IMPORT_LIST_IS_EMPTY);
        }
        SupplierImportRespVO respVO = SupplierImportRespVO.builder().createSuppliernames(new ArrayList<>())
                .updateSuppliernames(new ArrayList<>()).failureSuppliernames(new LinkedHashMap<>()).build();
        importSuppliers.forEach(importSupplier ->{
            // 校验，判断是否有不符合的原因
            try {
                validateSupplierForCreateOrUpdate(null,null);
            } catch (ServiceException ex) {
                respVO.getFailureSuppliernames().put(importSupplier.getName(), ex.getMessage());
                return;
            }
            // 判断如果不存在，再进行插入
            SupplierDO existSupplier = supplierMapper.selectByName(importSupplier.getName());

            if (existSupplier == null) {
                SupplierDO supplierDO = BeanUtils.toBean(importSupplier, SupplierDO.class);
                String groupNameReq = importSupplier.getGroupName();
                if (groupNameReq != null) {
                    SupplierGroupDO supplierGroupDO = supplierGroupMapper.selectByName(groupNameReq);
                    if (supplierGroupDO == null) {
                        supplierGroupDO.setName(groupNameReq);
                        supplierGroupMapper.insert(supplierGroupDO);
                    }
                    supplierDO.setGroupId(supplierGroupDO.getId()).setGroupName(groupNameReq);
                }
                supplierDO.setStatus(1);
                supplierMapper.insert(supplierDO);
//                crmPermissionService.createPermission(new CrmPermissionCreateReqBO().setBizType(CrmBizTypeEnum.CRM_Supplier.getType())
//                        .setBizId(supplierDO.getId()).setLevel(CrmPermissionLevelEnum.OWNER.getLevel()).setUserId(userId));
                respVO.getCreateSuppliernames().add(importSupplier.getName());
                return;
            }
            // 如果存在，判断是否允许更新
            if (!isUpdateSupport) {
                respVO.getFailureSuppliernames().put(importSupplier.getName(), SUPPLIER_SUPPLIERNAME_EXISTS.getMsg());
                return;
            }
            SupplierDO updateSupplier = BeanUtils.toBean(importSupplier, SupplierDO.class);
            updateSupplier.setId(existSupplier.getId());
            supplierMapper.updateById(updateSupplier);
            respVO.getUpdateSuppliernames().add(importSupplier.getName());
        });
        return respVO;

    }

}